package cn.ydxiaoshuai.sample.aisample.baidu.nlp;

import cn.hutool.http.HttpUtil;
import cn.ydxiaoshuai.sample.aisample.baidu.common.BaiDuConts;
import cn.ydxiaoshuai.sample.aisample.baidu.model.Couplets;
import cn.ydxiaoshuai.sample.aisample.baidu.model.CoupletsResponse;
import com.alibaba.fastjson.JSON;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;

/**
 * @author 小帅丶
 * @className CoupletsSample
 * @Description 智能写春联
 * @Date 2022-01-27-11:21
 **/
public class CoupletsSample {
    /** 字体 */
    private static String FONT_FAMILY = "华文行楷";

    public static void main(String[] args) throws Exception{
        //接口必要的AccessToken
        String accessToken = "";

        Couplets bean = new Couplets();
        bean.setText("虎年春节");
        //body参数转JSON
        String body = JSON.toJSONString(bean);

        /** 1、GBK支持：默认按GBK进行编码，输入内容为GBK编码，输出内容为GBK编码，否则会接口报错编码错误
         2、UTF-8支持：若文本需要使用UTF-8编码，请在url参数中添加charset=UTF-8 （大小写敏感）
         */
        //拼接URL参数
        String params = "charset=UTF-8&access_token="+accessToken;

        String result = HttpUtil.post(BaiDuConts.COUPLETS_URL + "?" + params, body);

        System.out.println("result = " + result);

        //生成春联图片
        getCouplets(result);
    }
    /**
     * @Author 小帅丶
     * @Description 生成春联图片
     * @Date  2022-01-27 11:36
     * @param couplets - 春联内容
     **/
    public static void getCouplets(String couplets) throws Exception{
        //字符串转对象
        CoupletsResponse coupletsResponse = JSON.parseObject(couplets,CoupletsResponse.class);
        long startTime = System.currentTimeMillis();
        //背景图
        BufferedImage image = ImageIO.read(new File("F:\\testimg\\couplet\\empty.jpg"));
        String markContent = coupletsResponse.getCouplets().getCenter();
        AttributedString ats = new AttributedString(markContent);
        Graphics2D g = (Graphics2D) image.getGraphics();
        // 横批文字填充
        Font font = new Font(FONT_FAMILY, Font.PLAIN, 110);
        g.setStroke(new BasicStroke(2.5f));
        g.setColor(new Color(255,229,83));
        g.setFont(font);
        /* 消除java.awt.Font字体的锯齿 */
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        /* 消除java.awt.Font字体的锯齿 */
        ats.addAttribute(TextAttribute.FONT, font, 0, markContent.length());
        AttributedCharacterIterator iter = ats.getIterator();
        g.drawString(iter,109,180);


        String markContentLeft =  coupletsResponse.getCouplets().getFirst();
        String markContentRight =  coupletsResponse.getCouplets().getSecond();

        setLeftRightContent(markContentLeft,g,"left");
        setLeftRightContent(markContentRight,g,"right");

        //不压缩图片质量进行保存
        ImageWriter writer = ImageIO.getImageWritersBySuffix("jpg").next();
        ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        //0-1范围 越大质量越高
        imageWriteParam.setCompressionQuality(1);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        writer.setOutput(new MemoryCacheImageOutputStream(output));
        writer.write(null,new IIOImage(image,null,null),imageWriteParam);
        writer.dispose();
        //最终图片保存路径
        FileOutputStream file = new FileOutputStream("F:\\testimg\\couplet\\couplets.jpg");
        file.write(output.toByteArray());
        System.out.println("总耗时"+(System.currentTimeMillis()-startTime));

    }
    /**
     * @Author 小帅丶
     * @Description 填充左右内容
     * @Date  2022-01-27 11:31
     * @param markContent - 对联内容
     * @param g - Graphics2D对象
     * @param direction - 对联方向-上联、下联
     **/
    private static void setLeftRightContent(String markContent, Graphics2D g, String direction) {
        Font font = new Font(FONT_FAMILY, Font.PLAIN, 60);
        for (int i = 0; i < markContent.length(); i++) {
            char singleWordChart = markContent.charAt(i);
            AttributedString singleWord = new AttributedString(String.valueOf(singleWordChart));
            g.setStroke(new BasicStroke(2.5f));
            g.setColor(new Color(255,229,83));
            g.setFont(font);
            /* 消除java.awt.Font字体的锯齿 */
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            /* 消除java.awt.Font字体的锯齿 */
            singleWord.addAttribute(TextAttribute.FONT, font, 0, String.valueOf(singleWordChart).length());
            AttributedCharacterIterator singleWordIterator = singleWord.getIterator();
            if(direction.equals("left")){
                if(i>0){
                    int height = i*65;
                    g.drawString(singleWordIterator,55,358+height);
                }else{
                    g.drawString(singleWordIterator,55,358);
                }
            }else{
                if(i>0){
                    int height = i*65;
                    g.drawString(singleWordIterator,530,358+height);
                }else{
                    g.drawString(singleWordIterator,530,358);
                }
            }

        }
    }

}
